netadmin.Lib = {}

--CONFIG FILE FUNCTIONS
function netadmin.Lib.PrepareConfigForUpload( strFile )
	local tblFile = string.Explode("\n", strFile)
	local newtable = {}
	for _,v in pairs(tblFile) do
		if string.find(string.Left(v,1), "%a") then --the 1st letter of any config "should" be a letter
			local foundlocation = string.find(v, "//")
			if foundlocation then
				table.insert(newtable, string.Left(v, foundlocation - 1))
			else
				table.insert(newtable, v)
			end
		end
	end
	
	return newtable
end


function netadmin.Lib.GetConfig( strGroup )
		local tblFileData = {}
		local tblQuery = {}
		tblQuery = gdatabase.Query("SELECT * FROM `config` WHERE `group`=\'" .. string.lower(strGroup) .. "\';", netadmin.DB)
		for int, value in pairs(tblQuery) do
			tblFileData[value[1]]  = value[3]
		end
		
		return tblFileData
end

function netadmin.Lib.GetAllConfigs()
	local tblGroups = {}
	local tblQuery = {}
	
	tblQuery = gdatabase.Query("SELECT DISTINCT(`group`) FROM `config`", netadmin.DB)
	for i, v in pairs(tblQuery) do
		tblGroups[v[1]] = netadmin.Lib.GetConfig( v[1] )
	end
	
	
	return tblGroups
end


function netadmin.Lib.GetConfigs()
	local tblConfigs = {}
	for i, v in pairs(netadmin.config.cfggroups) do
		table.insert(tblConfigs, "//" .. string.lower(v))
		table.Add(tblConfigs, netadmin.Lib.GetConfig(v))
	end
	
	return tblConfigs
end

function netadmin.Lib.SetConfig(strGroup)
	strGroup = strGroup or "common"
	strGroup = gdatabase.CleanString(netadmin.DB, string.lower(strGroup))
	local tblConfig = netadmin.Lib.PrepareConfigForUpload( file.Read("../addons/ulx/cfg/server.ini") )
	local intMaxIndex = table.getn(tblConfig)
	
	--1st lets purge the old config for the specified group
	gdatabase.Query("DELETE FROM `config` WHERE `group` = \'" .. strGroup .. "\';", netadmin.DB)
	
	--insert the config
	for i, v in ipairs(tblConfig) do 
		local strLine = gdatabase.CleanString(netadmin.DB, v)
		Msg("Sending line " .. tostring(i) .. "/" .. intMaxIndex .. "\n")
		gdatabase.Query("INSERT INTO `config` ( `group`, `data`) VALUES ( \'" .. strGroup .. "\', \'" .. strLine .. "\');", netadmin.DB)
	end
end

--returns the ID of the pattern
function netadmin.Lib.GetID(strLine)
	local theQuery = gdatabase.Query("SELECT id FROM `config` WHERE `data` = \"" .. strLine .. " \" LIMIT 1;", netadmin.DB)
	return theQuery[1][1]
end


